<template lang="pug">
  .main
    .title
      div(@click="closeOpened") 坐标系转换
      .button-group
        el-button(type="plain" size="mini" round @click="init('pick')") 地图选点
        el-button(type="plain" size="mini" round @click="init('input')") 输入坐标
        el-button(type="plain" size="mini" round @click="selectFiles") 选择文件
        input(type="file" multiple id="myFiles" style="display: none" v-on:input ="fileImport")
    .function-content(v-if="functionType==='pick'")
      span
      span 默认拾取GCJ02
      .coordinates
        .select-point
          el-input(v-model="pick_Coordinate" placeholder="" size="mini")
        .transform-point
          .point-coord
            span WGS84(GPS)
            el-input(v-model="coordinate_wgs84" placeholder="" size="mini")
            svg-icon(icon-class="location")
          .point-coord
            span GCJ02(高德)
            el-input(v-model="coordinate_gcj02" placeholder="" size="mini")
            svg-icon(icon-class="location")
          .point-coord
            span BD09(百度)
            el-input(v-model="coordinate_bd09"  placeholder="" size="mini")
            svg-icon(icon-class="location")
    .function-content(v-if="functionType==='input'") 输入坐标
    .function-content.select-file(v-if="functionType==='file'") 选择文件
      el-row
        el-col.input-textarea(:span="6")
          el-input(type="textarea" :rows="20" placeholder="请输入内容" v-model="selectTextArea")

        el-col.format-button(:span="2")
          el-button(@click="format" :disabled = "this.selectTextArea === ''") 格式化

        el-col.format-textarea(:span="6")
          el-input(type="textarea" :rows="20" placeholder="请输入内容" v-model="formatTextArea")

        el-col.trans-content(:span="3")

          el-select(v-model="fromCoordSys" clearable placeholder="原始坐标")
            el-option(v-for="item in coordSysOptions" :key="item.value" :label="item.label" :value="item.value")
          el-select(v-model="toCoordSys" clearable placeholder="目的坐标")
            el-option(v-for="item in coordSysOptions" :key="item.value" :label="item.label" :value="item.value")

          el-button(@click="transformCoord" :disabled = "this.selectTextArea === ''") 转换
          el-input(placeholder="文件名" v-model="fileName" clearable)
          el-button(@click="saveJson" :disabled = "this.resultTextArea === ''") 下载

        el-col.result-textarea(:span="6")
          el-input(type="textarea" :rows="20" placeholder="请输入内容" v-model="resultTextArea")


</template>

<script>
  import 'element-ui/lib/theme-chalk/base.css';
  import Transformer from "../../script/coordTransform"


  export default {
    name: "transformCoord",
    data() {
      return {
        dialog: {// dialog显示隐藏
          dialogVisible: false,
          dialogDrag: true, // 可拖拽
          dialogChange: true, // 可拉伸
          title: '详情'
        },
        functionType: '',//功能类型
        pickMarker:null,//当前点选的地图点
        pick_Coordinate: '',
        coordinate_wgs84: '',
        coordinate_gcj02: '',
        coordinate_bd09: '',


        isNest: true,
        isDisabled: false,
        fileName: '',
        newCoordinates: [],
        testJson: {
          "geometry": {
            "coordinates": [[119.65314822485131, 29.73600727691725], [119.65588787830542, 29.736499154251522]],
            "type": "LineString"
          },
          "type": "Feature",
          "properties": {
            "osm_id": "307301266",
            "fclass": "river", "centerPosition": "119.587037,29.7021489",
            "code": 8101,
            "width": 0,
            "name": "清渚港"
          }
        },

        selectTextArea: '',
        formatTextArea: '',
        resultTextArea: '',
        tempResult:'',
        textarea2: '',
        textarea3: '',
        show: false,
        coordSysOptions: [
            { value: 'gcj02', label: 'GCJ-02' },
            { value: 'bd09', label: 'BD-09' },
            { value: 'wgs84', label: 'WGS-84' }],

        value1: 'gcj02',
        value2: 'bd09',
        fromCoordSys:'gcj02',
        toCoordSys:'bd09',
        keyName: 'coordinates',
        isGo: true
      }

    },
    components: {
      // myViewer
    },
    created() {
      this.selectTextArea = JSON.stringify(this.testJson)
    },
    mounted() {
      // this.init(true)
    },
    watch: {
      fromCoordSys(){this.resultTextArea = ''},
      toCoordSys(){this.resultTextArea = ''},

      files() {
        this.fileImport();
      },
      pick_Coordinate(val){
        this.transPointCoord(this.value1,val);
      }
    },
    methods: {
      closeOpened(){
        this.functionType = '';
      },
      init(str) {
        leafletMap.off('click',this.onMapClick)
        this.functionType = str;
        switch (str) {
          case 'pick':
            leafletMap.on('click', this.onMapClick);
            break
          default:
            break
        }
      },

      onMapClick(e) {
        if (this.pickMarker) leafletMap.removeLayer(this.pickMarker);
        //点坐标
        this.pickMarker = L.marker([e.latlng.lat, e.latlng.lng],
          {
            title: "test-title",
            riseOnHover: true
          }).addTo(leafletMap);
        //弹窗信息
        let divHtml2 = "<b>the popup location is:</b><br>经度：" + e.latlng.lng.toFixed(3) + " 维度：" + e.latlng.lat.toFixed(3);
        this.pickMarker.bindPopup(divHtml2);//.openPopup()
        this.pick_Coordinate = e.latlng.lng.toFixed(9) + ',' + e.latlng.lat.toFixed(9)
      },
      //转换点坐标
      transPointCoord(curSys,arrStr){
        let arrItem = arrStr.split(',').map((val) => {
          return parseFloat(val)
        });
        this.coordSysOptions.forEach((item) => { //gcj bd wgs
          if (item.value === curSys) {
            this["coordinate_" + curSys] = arrStr
          } else {
            let functionName = curSys + "to" + item.value
            this["coordinate_" + item.value] = Transformer[functionName](arrItem[0], arrItem[1]).map((value)=>{
              return value.toFixed(9)
            }).join(',')
          }
        })
      },
      //批量选择文件
      selectFiles() {
        leafletMap.off('click',this.onMapClick)
        this.functionType = 'file'
        this.selectTextArea = '';
        this.formatTextArea = '';
        this.resultTextArea = '';
        document.getElementById("myFiles").click();
      },
      fileImport() {
        // console.log("触发了：")
        //获取读取我文件的File对象
        let files = document.getElementById("myFiles").files;
        for (let i = 0; i < files.length; i++) {
          let reader = new FileReader(); //新建一个FileReader
          reader.readAsText(files[i], "UTF-8"); //读取文件
          this.fileName = files[i].name.split('.')[0];
          reader.onload = () => { //读取文件之后会回来这里
            this.isNest = true;
            this.selectTextArea = reader.result;
          }
        }
      },
      format() {
        let tempJson = JSON.parse(this.selectTextArea); //转换成对象
        this.formatTextArea = JSON.stringify(tempJson, null, 2) //使用四个空格缩进
      },

      zoom() {
        this.show = !this.show;
      },

      transformCoord() {
        let jsonObj = JSON.parse(this.selectTextArea); //转换成对象
        if (jsonObj.type === 'FeatureCollection') {//多要素文件
          this.dealFeatureCollection(jsonObj);
        }

      },
      //处理多要素文件
      dealFeatureCollection(jsonObj){
        jsonObj.features.forEach((featureItem)=>{ //{type properties geometry}
          switch (featureItem.geometry.type) {
            case "MultiPolygon":
              featureItem.geometry.coordinates = this.dealMultiPolygon(featureItem.geometry.coordinates);
              break
            case "Polygon":
            case "MultiLineString":
              featureItem.geometry.coordinates = this.dealPolygon_MultiLineString(featureItem.geometry.coordinates);
              break
            case "LineString":
              featureItem.geometry.coordinates = this.dealCoordGroupArr(featureItem.geometry.coordinates); //坐标对数组
              break
            default:
              this.$message.error('不支持当前格式')
              break
          }
        })
        this.resultTextArea = JSON.stringify(jsonObj)
      },

      dealMultiPolygon(coordinates_MultiPolygon){
        if (coordinates_MultiPolygon.length > 2) return this.$message.error('不支持当前格式')
        coordinates_MultiPolygon[0].forEach((coordGroupArr,index)=>{
          coordinates_MultiPolygon[0][index] = this.dealCoordGroupArr(coordGroupArr)
        })
        return coordinates_MultiPolygon
      },

      dealPolygon_MultiLineString(coordinates_MultiLineString){
        coordinates_MultiLineString.forEach((coordGroupArr,index)=>{
          coordinates_MultiLineString[index] = this.dealCoordGroupArr(coordGroupArr)
        })
        return coordinates_MultiLineString
      },

      dealCoordGroupArr(coordGroupArr){
        let result = [];
        result = coordGroupArr.map((item) => {
          //选择转换坐标类别
          let functionName = this.fromCoordSys + "to" + this.toCoordSys
          return  Transformer[functionName](item[0], item[1]);
        })
        return result
      },

      saveJson() {
        if (this.fileName === '') return this.$message.warning("请输入下载文件名")
        let blob = new Blob([this.resultTextArea], {
          type: "text/plain;charset=utf-8"
        });
        let reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = (e) => {
          let a = document.createElement('a');
          a.download = this.fileName + '转换' + this.fromCoordSys + '_' + this.toCoordSys + ".json";
          a.href = e.target.result;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      }
    },
    destroyed() {
      leafletMap.off('click',this.onMapClick)
      mapBaseF.removeAllNtt();
      this.init(false);
    },

  }
</script>

<style lang="stylus" scoped>
  @import "~@/styles/coord-transform.styl"


</style>
